//
//  UIButton+CycleIndicator.m
//  CycleControlFunction
//
//  Created by 苹果笔记本 on 2020/6/17.
//  Copyright © 2020 cycle. All rights reserved.
//

#import "UIButton+CycleIndicator.h"
#import <objc/runtime.h>

static NSString *const kIndicatorViewKey = @"indicatorView";
static NSString *const kButtonTextObjectKey = @"buttonTextObject";

@implementation UIButton (CycleIndicator)

///显示indicator
- (void)cycle_showIndicator {
    UIActivityIndicatorView *indicatorView = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    indicatorView.center = CGPointMake(self.bounds.size.width / 2, self.bounds.size.height / 2);
    [indicatorView startAnimating];
    
    NSString *currentButtonText = self.titleLabel.text;
    objc_setAssociatedObject(self, &kButtonTextObjectKey, currentButtonText, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    objc_setAssociatedObject(self, &kIndicatorViewKey, indicatorView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    [self setTitle:@"" forState:UIControlStateNormal];
    self.enabled = NO;
    [self addSubview:indicatorView];
}
///显示indicator
- (void)cycle_showIndicatorForGray {
    UIActivityIndicatorView *indicatorView = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    indicatorView.center = CGPointMake(self.bounds.size.width / 2, self.bounds.size.height / 2);
    [indicatorView startAnimating];
    
    NSString *currentButtonText = self.titleLabel.text;
    
    objc_setAssociatedObject(self, &kButtonTextObjectKey, currentButtonText, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    objc_setAssociatedObject(self, &kIndicatorViewKey, indicatorView, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    [self setTitle:@"" forState:UIControlStateNormal];
    self.enabled = NO;
    [self addSubview:indicatorView];
}

///隐藏indicatorView
- (void)cycle_hideIndicatorView {
    NSString *currentButtonText = (NSString *)objc_getAssociatedObject(self, &kButtonTextObjectKey);
    UIActivityIndicatorView *indicatorView = (UIActivityIndicatorView *)objc_getAssociatedObject(self, &kIndicatorViewKey);
    [indicatorView removeFromSuperview];
    [self setTitle:currentButtonText forState:UIControlStateNormal];
    self.enabled = YES;
}

@end
